<?php
	require("Util.php");
	
	$stat = plainPageText();
	echo $stat;
	
	/*
		Stripped the html tags from the specified tag content  or
		remove the content of the specified tag in the
		specified text
		@param string $tag the tag name
		@param string $attr the tag attribute
		@param string $data the text
		@param boolean $isRemove whether the content should be removed
		@return string the new text
	 */
	function getContentInsideTag ($tag, $attr, $data, $isRemove) {
		$start_tag = "<".$tag;
		if (strlen($attr) > 0)
			$start_tag .= " ".$attr;
		$start_tag .= ">";
		$end_tag = "</".$tag.">";
	
		$new_data = "";
		$start_pos = stripos($data, $start_tag); 
		$first_pos = 0;
		while ($start_pos !== false) {
			$start_pos += strlen($start_tag);
			$end_pos = stripos($data, $end_tag, $start_pos);
			if ($end_pos !== false) {
				//grab data between start_pos and first_pos
				$new_data .= substr($data, $first_pos, $start_pos - $first_pos);
				if ($isRemove == false) {
					//grab text between start_pos and end_pos
					$txt = substr($data, $start_pos, $end_pos - $start_pos);
					$txt = strip_tags($txt);
					$new_data .= $txt;
				}
				//update the first_pos
				$first_pos = $end_pos;
				$start_pos = stripos($data, $start_tag, 
									 $end_pos + strlen($end_tag));
			} else {
				$start_pos = false;
			}
		}
		//grab text start from $first_pos
		$new_data .= substr($data,$first_pos);
		
		//remove empty pagetext tag
		$new_data = str_ireplace("<pagetext></pagetext>","",$new_data);
		
		return $new_data;
	}
	
	/*
		Cleaning all html tags inside the pagetext tag
	*/
	function plainPageText () {
	   $folder_name = $_POST["templateFile"];
	   $isImage = $_POST["isImage"];
	   
	   $folderpath = $GLOBALS['uploaddir']."/".$folder_name;
	   $input_file = $folderpath."/".$GLOBALS["wikibook"];//path for the wikified file
	   $data = file_get_contents($input_file);
	       
	   if (strcmp("true",strtolower($isImage)) == 0) {
		   echo "stripping html from page text <br />";
		   $new_data = getContentInsideTag("pagetext","",$data,false);
	   } else {
	   	   echo "stripping the content of pagetext <br />";
		   $new_data = getContentInsideTag("pagetext","",$data,true);
	   }
	   
	   echo "saving the new data <br />";
	   $fh = modifyFile($input_file, 'w') or die("can't open file");
	   fwrite($fh, $new_data);
	   fclose($fh);
	   
	   return "&msg=Finish processing the book&result=no error"; 
	}
?>